import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { v4 as uuidv4 } from 'uuid'
import type { CommonComponentProps, TextComponentProps, ImageComponentProps } from '@/defaultProps'

export interface ComponentsData {
  props: Partial<TextComponentProps & ImageComponentProps>
  // props: CommonComponentProps
  id: string
  name: string
}
interface EditorProps {
  // 编辑器中的元素
  components: ComponentsData[]
  // 正在编辑的元素,component.id
  currentElement: string
}

const testComponents: ComponentsData[] = [
  {
    id: uuidv4(),
    name: 'l-text',
    props: {
      text: 'hello',
      color: '#000000',
      fontSize: '20px',
      lineHeight: '1',
      fontFamily: '',
      textAlign: 'center',
      opacity: '1',
      borderColor: '',
      backgroundColor: '',
      fontWeight: 'bold'
    }
  },
  {
    id: uuidv4(),
    name: 'l-text',
    props: {
      text: 'hello2',
      fontSize: '26px',
      lineHeight: '1',
      fontFamily: '',
      textAlign: 'center',
      opacity: '1'
    }
  },
  {
    id: uuidv4(),
    name: 'l-text',
    props: {
      text: 'hello3',
      fontSize: '29px',
      lineHeight: '1',
      fontFamily: '',
      actionType: 'url',
      url: 'https://baidu.com',
      textAlign: 'center',
      opacity: '1'
    }
  }
]

export const useEditorStore = defineStore('editor', () => {
  const editor = ref<EditorProps>({
    components: testComponents,
    currentElement: ''
  })
  const getCurrentElement = computed(() => {
    const currentElement = editor.value.components.find(
      (item) => item.id === editor.value.currentElement
    )
    if (!currentElement) {
      return null
    }
    return currentElement
  })
  const addComponent = (componentData: ComponentsData) => {
    editor.value.components.push(componentData)
  }
  const deleteComponent = (id: string) => {
    if (editor.value.currentElement === id) {
      editor.value.currentElement = ''
    }
    editor.value.components = editor.value.components.filter((item) => item.id !== id)
  }
  const setActive = (id: string) => {
    editor.value.currentElement = id
  }
  const updateComponent = ({ key, value }: { key: keyof TextComponentProps; value: any }) => {
    const currentElement = editor.value.components.find(
      (item) => item.id === editor.value.currentElement
    )
    if (!currentElement) {
      return false
    }
    currentElement.props[key] = value
  }
  // const doubleCount = computed(() => count.value * 2)
  // function increment() {
  //   count.value++
  // }

  return { editor, addComponent, deleteComponent, setActive, getCurrentElement, updateComponent }
})
